<template>
    <div ref="chartView" :style="{ width: '100%', height: '100%' }"></div>
</template>

<script>
import * as echarts from "echarts";
export default {
    name: 'EchartsCreator',
    props: {
        options: {
            type: Object,
            required: true
        },
    },
    data() {
        return {
            chart: null,
            resizeFn: null
        }
    },
    watch: {
        options: {
            deep: true,
            handler() {
                this.updataOptions();
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.initChart();
            this.updataOptions();
        })
    },
    methods: {
        initChart() {  
            let type = Object.prototype.hasOwnProperty.call(this.$attrs,'dark') ? 'dark' : '';
            // let type = this.$attrs.hasOwnProperty('dark') ? 'dark' : '';
            this.chart = echarts.init(this.$refs.chartView, type);
            this.resizeFn = () => {
                this.chart.resize();
            }
            window.addEventListener('resize', this.resizeFn)
        },
        updataOptions() {
            this.chart.clear();
            this.options && this.chart.setOption(this.options);
        },
        setOption(options) {
            this.chart.setOption(options);
        }
    },
    beforeDestroy() {
        // 解绑
        window.removeEventListener('resize', this.resizeFn);
        // 内存释放
        this.chart.dispose();
    }
}
</script>
<style scoped></style>